#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
script usage:
    python gitpull.py
"""
import optparse
import os
import subprocess
import sys


class Git(object):
    """
    Interact with git, provides clone, pull, etc.

    Reference: https://github.com/pexpect/pexpect
    """

    def __init__(self, cwd=None, env=None, git='/usr/bin/git'):
        self.cwd = cwd
        self.env = env
        self.git = git

    def pull(self, repo=None, origin=None):
        args = [self.git, 'pull']
        if repo:
            args.append(repo)
            if origin:
                args.append(origin)
        elif origin:
            args.append('origin')
            args.append(origin)
        self._call(args)

    def clone(self, repo, dir=None):
        args = [self.git, 'clone', repo]
        if dir:
            args.append(dir)
        self._call(args)

    def _call(self, args):
        print(' '.join(args))
        kwargs = dict(stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT, cwd=self.cwd, env=self.env)
        proc = subprocess.Popen(args, **kwargs)
        output, unused_err = proc.communicate()
        retcode = proc.poll()
        sys.stdout.write(output)
        # print('ret: %d' % retcode)


def compose(repo, username=None, password=None):
    """Compose username and password to https repo url."""
    if not username and not password:
        return repo
    if not repo or not repo.startswith('https://'):
        return repo

    usr, pwd = None, None

    from urlparse import urlparse, urlunparse
    url = urlparse(repo)

    parts = url.netloc.split('@')

    if len(parts) > 1:
        infos = parts[0].split(':')
        usr = infos[0]
        if len(infos) > 1:
            pwd = infos[1]

    if username: usr = username
    if password: pwd = password

    if not usr:
        return repo

    net = parts[-1]
    if pwd:
        netloc = '%s:%s@%s' % (usr, pwd, net)
    else:
        netloc = '%s@%s' % (usr, net)

    data = (url[0], netloc) + url[2:]
    return urlunparse(data)


def gitpull(cwd=None, url=None, usr=None, pwd=None, origin=None):
    git = Git(cwd)
    repo = compose(url, usr, pwd)
    git.pull(repo, origin)


def _parse_args():
    parser = optparse.OptionParser()
    parser.add_option('-d', '--cwd', dest='cwd')
    parser.add_option('-l', '--url', dest='url')
    parser.add_option('-u', '--usr', dest='usr', metavar='USERNAME')
    parser.add_option('-p', '--pwd', dest='pwd', metavar='PASSWORD')
    parser.add_option('-o', '--ori', dest='origin')
    options, args = parser.parse_args()
    return options


if __name__ == '__main__':
    options = _parse_args()
    # print(options.__dict__)
    gitpull(**options.__dict__)
